<?php
namespace App\Api\Fcjd;

use PhalApi\Api;

/**
 * Kami接口
 * @desc 读取phone_kami表数据
 */
class Kami extends Api {
    public function getRules() {
        return array(
            'getList' => array(
                'page' => array('name' => 'page', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '页码'),
                'page_size' => array('name' => 'page_size', 'type' => 'int', 'min' => 1, 'max' => 500, 'require' => true, 'desc' => '每页数量')
            ),
            'createKami' => array(
                'count' => array('name' => 'count', 'type' => 'int', 'min' => 1, 'max' => 500,  'require' => true, 'desc' => '生成数量'),
                'type' => array('name' => 'type', 'type' => 'int', 'min' => 1, 'max' => 999, 'require' => true, 'desc' => '卡密类型'),
                'rebate' => array('name' => 'rebate', 'type' => 'int', 'min' => 0, 'max' => 999, 'require' => false, 'desc' => '送卡时长'),
                'note' => array('name' => 'note', 'type' => 'string', 'desc' => '备注信息'),
                'user_id' => array('name' => 'user_id', 'type' => 'int', 'desc' => '用户ID'),
                'username' => array('name' => 'username', 'desc' => '用户名')
            ),
            'assignment' => array(
                'ids' => array('name' => 'ids', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 'require' => true, 'desc' => '数组格式的ID列表'),
                'note' => array('name' => 'note', 'type' => 'string', 'desc' => '备注信息'),
                'user_id' => array('name' => 'user_id', 'type' => 'int', 'desc' => '用户ID'),
            )
        );
    }

    /**
     * 获取kami列表
     * @desc 获取phone_kami表数据
     * @return array items 数据列表
     * @return int total 总记录数
     */
    public function getList() {
        $page = $this->page;
        $pageSize = $this->page_size;
        
        $total = \PhalApi\DI()->notorm->phone_kami->count();
        $items = \PhalApi\DI()->notorm->phone_kami
            ->select('*')
            ->order('id DESC')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->fetchAll();
            
        \PhalApi\DI()->response->addResult('success', true);
        return array('items' => $items, 'total' => $total, 'page' => $page, 'page_size' => $pageSize);
    }
    
    /**
     * 创建卡密
     * @desc 创建指定数量的卡密
     * @return array success 是否成功
     * @return array count 创建数量
     */
    public function createKami() {
        $count = $this->count;

        $duration_type = $this->type + $this->rebate;
        //只读取一次用户信息
        $userInfo = null;
        if (isset($this->user_id) && !empty($this->user_id)) {
            $userInfo = \PhalApi\DI()->notorm->phalapi_user->where('id', $this->user_id)->fetchOne();
        }

        $successCount = 0;
        for ($i = 0; $i < $count; $i++) {
            $cardCode = $this->generateShortUUID();
            $data = array(
                'card_code' => $cardCode,
                'type' => $this->type,
                'duration_type' => $duration_type,
                'status' => 0,
                'expire_time' => date('Y-m-d H:i:s', strtotime('+365 days')),
                'create_time' => date('Y-m-d H:i:s')
            );
            //每张卡密都关联用户信息
            if ($userInfo && isset($userInfo['nickname'])) {
                $data['nickname'] = $userInfo['nickname'];
            }
            if (isset($this->note) && !empty($this->note)) {
                $data['note'] = $this->note;
            }
            if (isset($this->user_id) && !empty($this->user_id)) {
                $data['user_id'] = $this->user_id;
            }
            //如果没有传入用户名，则从用户信息中获取
            if ($userInfo && isset($userInfo['username'])) {
                $data['username'] = $userInfo['username'];
            }
 
            
            $result = \PhalApi\DI()->notorm->phone_kami->insert($data);
            if ($result) {
                $successCount++;
            }
        }
        
        \PhalApi\DI()->response->addResult('success', true);
        return array('success' => true, 'count' => $successCount);
    }
    
    /**
     * 生成短UUID
     * @return string 16位唯一ID
     */
    private function generateShortUUID() {
        $data = random_bytes(12);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
        $timestamp = substr(hash('sha1', microtime(true)), 0, 4);
        return 'F' . strtoupper(substr(bin2hex($data), 0, 11) . $timestamp);
    }
    
    /**
     * 分配卡密
     * @desc 批量更新卡密记录
     * @return array success 是否成功
     * @return array count 更新数量
     */
    public function assignment() {
        $ids = $this->ids;
        $userInfo = null;
        
        if (isset($this->user_id) && !empty($this->user_id)) {
            $userInfo = \PhalApi\DI()->notorm->phalapi_user->where('id', $this->user_id)->fetchOne();
        }
        
        $data = array();
        if (isset($this->note) && !empty($this->note)) {
            $data['note'] = $this->note;
        }
        if (isset($this->user_id) && !empty($this->user_id)) {
            $data['user_id'] = $this->user_id;
        }
        //每张卡密都关联用户信息
        if ($userInfo && isset($userInfo['nickname'])) {
            $data['nickname'] = $userInfo['nickname'];
        }
        if ($userInfo && isset($userInfo['username'])) {
            $data['username'] = $userInfo['username'];
        }
        
        if (empty($data)) {
            throw new \PhalApi\Exception\BadRequestException('没有可更新的数据');
        }
        
        $count = \PhalApi\DI()->notorm->phone_kami
            ->where('id', $ids)
            ->update($data);
            
        \PhalApi\DI()->response->addResult('success', true);
        return array('success' => true, 'count' => $count);
    }
}